<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Requests;

use App\Services\DictionaryService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

/**
 * 广告位模块表单验证
 * Class AdsSpaceRequest
 * @package App\Http\Requests
 */
class AdsSpaceRequest extends BaseRequest
{

    /**
     * 注入表单请求验证时自动校验
     *
     * @var bool
     */
    public $autoValidate = false;

    /**
     * 用户是否有权操作，true是，false否
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 字段验证规则
     *
     * @return array
     */
    public function rules()
    {
        $ads_space = $this->ads_space;
        return [
            'id' => 'required|integer',
            'created_user_id' => 'required|integer',
            'name' => ['required', 'min:2', 'max:50', Rule::unique('ads_space')->ignore($ads_space)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'id_name' => ['nullable', 'min:2', 'max:100', 'regex:/^[a-zA-Z]+$/', Rule::unique('ads_space')->ignore($ads_space)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'type' => [
                'required',
                'integer',
                Rule::in(DictionaryService::getItemsValuesArray('adsSpaceTypeVar')),
            ],
            'width' => 'nullable|integer',
            'height' => 'nullable|integer',
            'status' => 'required|boolean',
            'description' => 'nullable|max:200'
        ];
    }

    /**
     * 提示信息
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }

    /**
     * 定义场景
     * @var \string[][]
     */
    public $scenes = [
        'store' => ['created_user_id', 'name', 'id_name', 'type', 'width', 'height', 'description', 'status'],
        'update' => ['name', 'id_name', 'type', 'width', 'height', 'description', 'status'],
        'destroy' => ['id'],
        'updateStatus' => ['status']
    ];

    /**
     * 验证错误的自定义属性
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'id' => __('common.id'),
            'name' => __('adsSpace.id'),
            'id_name' => __('adsSpace.id_name'),
            'type' => __('adsSpace.type'),
            'width' => __('adsSpace.width'),
            'height' => __('adsSpace.height'),
            'description' => __('adsSpace.description'),
            'status' => __('common.status'),
        ];
    }


    /**
     * 验证前
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->offsetSet('created_user_id', Auth::id());
        if (!isset($this->width) || empty($this->width)) $this->offsetSet('width', 0);
        if (!isset($this->height) || empty($this->height)) $this->offsetSet('height', 0);
    }
}
